"use strict"
const Controller = require("egg").Controller
const {sendStat, genRandomStr} = require("../extend/helper")
let promLogin = require("../extend/promLogin1")

const jsonwebtoken = require("jsonwebtoken")
let path = require("path")
let fs = require("fs")
let fileHelp = require("../extend/fileHelp")

class WxServerController extends Controller {
	constructor(ctx) {
		super(ctx)
		this.Application = this.app.model.Application
		this.constant = this.config.constant
		this.userCache = this.service.userCache
		this.serverConfig = this.config.serverConfig
	}
	/* 	async messageHandle() {
	
		} */
	async getJsCode() {
		let {ctx} = this
		ctx.validate({code: "string", aid: "pintstr"}, ctx.request.body)
		let {aid, code} = ctx.request.body
		let appInfo = (await ctx.app.cache.application).find(function (o) {
			return o.id == aid
		})
		if (!appInfo) {
			let e = new Error("没有app")
			e.field = "app_id"
			e.code = "missing_app"
			ctx.throw(422, "no has app", {
				code: "invalid_param",
				errors: [e],
			})
			return
		}
		let {app_secret, app_id} = appInfo
		let data
		try {
			data = await promLogin.getCode2accessToken({appid: app_id, secret: app_secret, js_code: code}) // 隐藏的reject
		} catch (error) {
			ctx.logger.error(error)
			ctx.body = sendStat(this.config.constant.WECHAT_CODE_REUSE, error && error.data)
			return
		}
		let {openid, unionid} = data  // 文档写的是 uinionid // 跟我i不一样
		ctx.logger.info(JSON.stringify({code, openid}))
		let obj = await this.service.moduleApplicat.createUserProm({aid: appInfo.id, openid: openid, unionid: unionid})
		obj.token = jsonwebtoken.sign({app_id, random: genRandomStr(20), openid, oid: obj.oid, aid: appInfo.id}, this.config.serverConfig.authKey,
			{
				expiresIn: this.config.serverConfig.tokenTime
			})
		await this.userCache.setWxSession(obj.oid, {openid})
		obj.ip = this.ctx.get("X-Real-IP")
		this.app.redis.publish("ip", JSON.stringify({ip: obj.ip}))
		ctx.body = sendStat(this.config.constant.NORMAL, obj)
	}

	async getAppInfo() {
		this.ctx.validate({aid: "pintstr"}, this.ctx.query)
		let applications = await this.app.cache.application
		let app = applications.find((v) => {
			return v.id == this.ctx.query.aid
		})
		if (!app) {
			this.ctx.body = sendStat(this.constant.ERROR_APP_NOEXIST)
		} else {
			let imgServer = this.config.serverConfig.imgServer
			let {applicat_name: name, head_url, qrcode_url, version} = app
			this.ctx.body = sendStat(this.constant.NORMAL, {name, head_url: imgServer + head_url, qrcode_url: imgServer + qrcode_url, version})
		}
	}

	async getQrCodeImg() {
		let downPath = "shf/"
		let oid = this.ctx.userInfo.oid
		let sharePath = path.join(this.serverConfig.uploadPath, downPath, oid + ".png")
		let shareExist = await fileHelp.exists(sharePath)
		if (!shareExist) {
			try {
				let data = await (this.ctx.wechatAccount.getWXACodeUnlimit({
					scene: {
						action: "invite",
						inviteId: oid
					}
				}))
				data.pipe(fs.createWriteStream(sharePath))
			}
			catch (e) {
				this.ctx.body = sendStat(this.constant.WECHAT_GENIMG_FAIL)
			}
		}
		this.ctx.body = sendStat(this.constant.NORMAL, {img_url: this.serverConfig.imgServer + this.serverConfig.imgBase + downPath + oid + ".png"})
		return
	}
}
module.exports = WxServerController